package com.soul.soulservice.service.imp;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soul.soulcommon.detail.DoctorDetail;
import com.soul.soulcommon.detail.GuardianDetail;
import com.soul.soulcommon.dto.Jwt;
import com.soul.soulcommon.dto.LoginRequest;
import com.soul.soulcommon.dto.RegisterRequest;
import com.soul.soulcommon.result.Result;
import com.soul.soulcommon.utils.JwtUtils;
import com.soul.souldao.domain.Doctor;
import com.soul.souldao.domain.Guardian;
import com.soul.souldao.mapper.DoctorMapper;
import com.soul.souldao.mapper.GuardianMapper;
import com.soul.soulservice.service.DoctorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.print.Doc;

@Slf4j
@Service
public class DoctorServiceImp extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {

    @Autowired
    @Qualifier("doctorAuthenticationManager")
    private AuthenticationManager doctorAuthenticationManager;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private DoctorMapper doctorMapper;
    @Override
    public String login(LoginRequest request) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(request.getUserName(), request.getPassword());
        Authentication authenticate = doctorAuthenticationManager.authenticate(authenticationToken);
        DoctorDetail doctorUserDetail = (DoctorDetail)  authenticate.getPrincipal();
        String principal = "用户名" + doctorUserDetail.getJwt().getUserName() + "登录成功";
        log.info(principal);
        Jwt older = doctorUserDetail.getJwt();
        return jwtUtils.generateToken(older.getId(), older.getUserName(), older.getRoleName());
    }
    @Override
    public Result<String> register(RegisterRequest registerRequest) {
        Doctor  dataDoctor = doctorMapper.selectOne(new LambdaQueryWrapper<Doctor>().eq(Doctor::getUserName, registerRequest.getUserName()));
        if(dataDoctor != null){
            return Result.error("用户名已存在");
        }
        //没有存在，可以注册
        Doctor doctor = new Doctor();
        doctor.setUserName(registerRequest.getUserName());
        doctor.setPassword(registerRequest.getPassword());
        doctor.setRoleName(registerRequest.getRoleName());
        doctor.setEmail(registerRequest.getEmail());
        if(doctorMapper.save(doctor)) {
            return Result.success("注册成功");
        }
        return Result.error("注册失败请联系工作人员");
    }
}
